/*
 * Copyright 2013-2019 Xia Jun(3979434@qq.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 ***************************************************************************************
 *                                                                                     *
 *                        Website : http://www.farsunset.com                           *
 *                                                                                     *
 ***************************************************************************************
 */
package com.farsunset.lvxin.service.impl;

import com.farsunset.cim.sdk.server.handler.CIMNioSocketAcceptor;
import com.farsunset.cim.sdk.server.model.CIMSession;
import com.farsunset.lvxin.data.redis.SessionRedisTemplate;
import com.farsunset.lvxin.data.repository.SessionRepository;
import com.farsunset.lvxin.service.CIMSessionService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Service
public class CIMSessionServiceImpl implements CIMSessionService {

    @Resource
    private SessionRepository sessionRepository;

    @Resource
    private SessionRedisTemplate sessionRedisTemplate;

    @Resource
    private CIMNioSocketAcceptor cimNioSocketAcceptor;

    @Value("#{'${server.host}'.trim()}")
    private String host;

    @Override
    public void save(CIMSession session) {
        sessionRepository.saveAndFlush(session);
        sessionRedisTemplate.save(session);
    }

    @Override
    public CIMSession get(String account) {

        CIMSession session = sessionRedisTemplate.get(account);
        if (session == null) {
            session = sessionRepository.findOne(account);
            sessionRedisTemplate.saveOrRemove(account, session);
        }

        if (session != null && (Objects.equals(session.getHost(), host.trim()))) {
            session.setSession(cimNioSocketAcceptor.getManagedSession(session.getNid()));
        }

        return session;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void remove(String uid) {
        sessionRepository.deleteById(uid);
        sessionRedisTemplate.delete(uid);
    }

    @Override
    public Page<CIMSession> queryPage(CIMSession session, Pageable page) {

        session.cleanEmptyProperties();

        ExampleMatcher matcher = ExampleMatcher.matching().withIgnorePaths("apns")
                .withMatcher("deviceModel", ExampleMatcher.GenericPropertyMatchers.ignoreCase()).withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING);

        return this.sessionRepository.findAll(Example.of(session, matcher), page);
    }

}
